package com.hd.manager.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hd.appcommon.constant.RoleConstant;
import com.hd.appcommon.entity.*;
import com.hd.appcommon.entity.vo.SelectVo;
import com.hd.appcommon.service.*;
import com.hd.hdxgddcommon.annotation.api.SysLogBuilder;
import com.hd.hdxgddcommon.controller.AbstractController;
import com.hd.hdxgddcommon.entity.dto.ResultDto;
import com.hd.hdxgddcommon.page.MyPage;
import com.hd.hdxgddcommon.utils.GenerateIdUtils;
import com.hd.hdxgddcommon.utils.StringUtils;
import com.hd.manager.shiro.token.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
public class RoleController extends AbstractController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IRolePrivilegeService rolePrivilegeService;
    @Autowired
    private IOrgMemberRoleService memberRoleService;
    @Autowired
    private IPrivilegeService privilegeService;
    @Autowired
    private RoleDeptService roleDeptService;
    @Autowired
    private TeacherService teacherService;


    @RequestMapping("/role/list")
    public ResultDto list(MyPage<Role> page, String roleName, Integer roleStatus) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(roleName))
            wrapper.like(Role::getRoleName, roleName);
        if (roleStatus != null)
            wrapper.eq(Role::getRoleStatus, roleStatus);
        wrapper.orderByDesc(Role::getCreateTime);
        roleService.page(page, wrapper);
        return success(page);
    }

    @RequestMapping("/role/save")
    @SysLogBuilder(value = "新增")
    public ResultDto save(Role role, String[] privilegeIds, String[] teacherDept, String[] stuDept) {

        if (null == role || null == privilegeIds)
            return fail("请求参数异常或未选择权限!");
        Role unique = roleService.getUnique(role.getRoleName());
        if (unique == null) {
            Date date = new Date();
            String roleId = GenerateIdUtils.get32Varchar();
            role.setRoleId(roleId)
                    .setCreateTime(date)
                    .setModifyTime(date)
                    .setRoleStatus(RoleConstant.STATUS.ABLE);
            boolean save = roleService.save(role, Arrays.asList(privilegeIds));
            if (save) {
                roleDeptService.insertTeacherAndStuDept(role.getRoleId(), teacherDept, stuDept);

            }
            return save ? success() : fail();
        } else {
            return fail("角色名不能重复!");
        }
    }

    @RequestMapping("/role/edit")
    @SysLogBuilder(value = "修改指定角色的权限")
    public ResultDto edit(Role role, String[] privilegeIds, String[] teacherDept, String[] stuDept) {
        if (role == null) return fail("请求参数异常!");
        Role unique = roleService.getUnique(role.getRoleName());
        if (unique == null || unique.getRoleId().equals(role.getRoleId())) {
            Date date = new Date();
            role.setModifyTime(date);
            boolean update = roleService.edit(role, Arrays.asList(privilegeIds));
            if (update) {
                // 删除原先role Id的
                roleDeptService.remove(new QueryWrapper<RoleDept>()
                        .eq("role_id", role.getRoleId()));
                roleDeptService.insertTeacherAndStuDept(role.getRoleId(), teacherDept, stuDept);
            }
            return update ? success() : fail();
        } else {
            return fail("角色名不能重复!");
        }
    }

    /**
     * @return 角色分配权限 获取当前角色的所有权限
     */
    @RequestMapping("/role/privileges/checked")
    public ResultDto privilegesByRoleId(String roleId) {
        List<Privilege> privileges = privilegeService.listByRoleId(roleId);
        List<String> checkeds = privileges.stream()
                .map(Privilege::getPrivilegeId)
                .collect(Collectors.toList());
        return checkeds.isEmpty() ? fail() : success(checkeds);
    }

    /**
     * @return 角色分配教职工部门 获取当前角色的所有教职工
     */
    @RequestMapping("/role/privileges/checked/teachers")
    public ResultDto teacherDeptByRoleId(String roleId) {
        QueryWrapper<RoleDept> roleDeptQueryWrapper = new QueryWrapper<RoleDept>()
                .eq("role_id", roleId)
                .eq("dept_type", 1);
        List<RoleDept> depts = roleDeptService.list(roleDeptQueryWrapper);
        List<String> checkeds = depts.stream()
                .map(roleDept -> roleDept.getDept().toString())
                .collect(Collectors.toList());
        return checkeds.isEmpty() ? fail() : success(checkeds);
    }

    /**
     * @return 角色分配教学生部门 获取当前角色的所有学生部门
     */
    @RequestMapping("/role/privileges/checked/stus")
    public ResultDto stuDeptByRoleId(String roleId) {
        QueryWrapper<RoleDept> roleDeptQueryWrapper = new QueryWrapper<RoleDept>()
                .eq("role_id", roleId)
                .eq("dept_type", 2);
        List<RoleDept> depts = roleDeptService.list(roleDeptQueryWrapper);
        List<String> checkeds = depts.stream()
                .map(roleDept -> roleDept.getDept().toString())
                .collect(Collectors.toList());
        return checkeds.isEmpty() ? fail() : success(checkeds);
    }

    /**
     * @return 获取当前角色对应的所有管理员 , 分配管理员
     */
    @RequestMapping("/role/members")
    public ResultDto members(@RequestParam String roleId) {
        List<Teacher> memberList = teacherService.list();
        List<Teacher> members = teacherService.listByRoleId(roleId);
        // 当前角色已经有的管理员
        List<String> memberIds = members.stream()
                .map(teacher -> teacher.getId().toString())
                .collect(Collectors.toList());
        // 全部的管理员
        List<SelectVo> allMember = memberList.stream()
                .map(a -> new SelectVo(a.getName(), a.getId().toString()))
                .collect(Collectors.toList());
        Map<String, Object> result = new HashMap<>();
        result.put("memberList", allMember);
        result.put("checked", memberIds);
        return success(result);
    }

    @RequestMapping("/role/edit/members")
    @SysLogBuilder(value = "批量对管理员分配指定角色")
    public ResultDto editAdmins(@RequestParam String roleId, String[] memberIds) {
        Role role = roleService.getById(roleId);
        if (role == null) return fail("没有找到对应的角色!");
        boolean edit = roleService.editMember(roleId, memberIds);
        return edit ? success() : fail();
    }

    @RequestMapping("/role/remove")
    @SysLogBuilder(value = "删除指定角色")
    public ResultDto remove(@RequestParam String roleId) {
        LambdaQueryWrapper<OrgMemberRole> wrapper0 = new LambdaQueryWrapper<>();
        wrapper0.eq(OrgMemberRole::getRoleId, roleId).last(" limit 1 ");
        OrgMemberRole one = memberRoleService.getOne(wrapper0);
        if (one != null) {
            return fail("该角色已被使用!");
        }
        boolean remove = roleService.removeById(roleId);
        if (remove) {
            LambdaQueryWrapper<RolePrivilege> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(RolePrivilege::getRoleId, roleId);

            rolePrivilegeService.remove(wrapper1);
            // 删除对应部门
            roleDeptService.remove(new QueryWrapper<RoleDept>()
                    .eq("role_id", roleId));
        }
        return remove ? success() : fail();
    }
    @RequestMapping("/role/getRoleIdByMemberId")
    public ResultDto getRoleIdByMemberId(){
        User token = TokenManager.getToken();
        QueryWrapper<OrgMemberRole> OrgMemberRoleQueryWrapper = new QueryWrapper<OrgMemberRole>()
                .eq("org_member_id", token.getId());
        OrgMemberRole roleid = memberRoleService.getOne(OrgMemberRoleQueryWrapper);
        return roleid==null ? fail() : success(roleid);
    }

}
